package com.habdqn.jspdemo.im.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;

/**
 * @author Administrator
 */
@WebFilter(filterName = "BaseFilter",urlPatterns = "/*",
        initParams={@WebInitParam(name = "encoding",value = "utf-8")})
public class BaseFilter implements Filter {
    private FilterConfig filterConfig;

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //在请求到达Servlet之前进行的预处理
        //获取请求的上下文
      /*  ServletContext context = filterConfig.getServletContext();
        System.out.println("请求的路径："+((HttpServletRequest)req).getServletPath());
        System.out.println("请求的类型："+((HttpServletRequest)req).getMethod());
        long begin = System.currentTimeMillis();
        System.out.println("请求到达Filter的时间："+begin);*/

        //设置请求与响应的编码
        String encoding = filterConfig.getInitParameter("encoding");
        req.setCharacterEncoding(encoding);
        resp.setCharacterEncoding(encoding);

        //向后一个过滤器或者Servlet传递请求
        chain.doFilter(req, resp);
        //在响应到达客户端之前进行相关处理

       /* long end = System.currentTimeMillis();
        System.out.println("响应到达Filter的时间："+end);
        System.out.println("所花时间："+(end-begin));*/

    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        this.filterConfig = config;
    }

}
